package cn.netuo.bumbersoll;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;

import com.rooten.frame.AppActivity;

import java.util.List;

import lib.grasp.util.BarUtils;
import lib.grasp.util.L;
import lib.grasp.util.TOAST;
import lib.grasp.widget.ProhibitViewGroup;
import lib.grasp.widget.SwipeItemLayout;
import lib.grasp.widget.decoration.DecorationGrid;

/**
 * Created by JS_grasp on 2019/3/18.
 * 1. 选择蓝牙
 */
public class SelectBleActivity extends AppActivity implements View.OnClickListener{

    /** 蓝牙适配器 */
    private BluetoothAdapter mBluetoothAdapter;

    /** 蓝牙搜索回调 */
    private BluetoothAdapter.LeScanCallback mLeScanCallback = this::onScan;

    private Handler mHandler = new Handler();

    private View                    mView;
    private List<BluetoothDevice>   mDatas;
    private SelectBleAdapter        mAdapter;


    /** wm */
    private WindowManager mWindowManager;
    /** 禁用下拉菜单辅助类 */
    private ProhibitViewGroup mProhibitViewGroup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mView = LayoutInflater.from(this).inflate(R.layout.activity_select_ble, null);
        installView(mView, 1);

//        initView();
        initRecyclerView();

        adjustToLoadOrSwitch();

        mWindowManager = ((WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE));


//        PermissionRxUtil.checkDangerousPermission(this, Manifest.permission.SYSTEM_ALERT_WINDOW);
//        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
//        intent.setData(Uri.parse("package:" + getPackageName()));
//        startForResult(intent, new IResultListener() {
//            @Override
//            public void onResult(int resultCode, Intent data) {
//                if(mWindowManager != null) mProhibitViewGroup = BarUtils.prohibitStatusPanelDropDown(SelectBleActivity.this, mWindowManager);
//            }
//        });
    }

    @Override
    protected void initActionMenu(MenuItem item) {
        super.initActionMenu(item);
        item.setVisible(false);
        setTitle("选择蓝牙设备");
        mToolbar.setNavigationIcon(null);
    }

    private void initView() {
        App.getApp().getBatteryReceiver().getBatteryLeftRate(this);
    }

    private void initRecyclerView() {
        mAdapter = new SelectBleAdapter(this, this);
        mAdapter.setBg(mView.findViewById(R.id.iv_bg));
        mDatas = mAdapter.getDatas();
        RecyclerView mRecyclerView = mView.findViewById(R.id.recyclerview);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        Drawable d = new ColorDrawable(Color.parseColor("#ececec"));
        DecorationGrid divider = new DecorationGrid(this,1,d);
        mRecyclerView.addItemDecoration(divider);

        mRecyclerView.addOnItemTouchListener(new SwipeItemLayout.OnSwipeItemTouchListener(this));
        mRecyclerView.setAdapter(mAdapter);
    }

    private void initBt(){
        if(mBluetoothAdapter == null){
            BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
            mBluetoothAdapter = bluetoothManager.getAdapter();
        }
        if(mBluetoothAdapter == null) return;

        if(!mBluetoothAdapter.isEnabled()){     // 蓝牙没开
            L.logOnly("--蓝牙并没有没开");
            initBleAdapter();
            return;
        }
    }

    /** 延迟开始扫描任务 */
    private void doLoad(){
        mHandler.postDelayed(() -> {
            L.logOnly("--之前并没有连接过指定设备");
            doScan();

        }, 2000 * 1);
    }

    /** 扫描 */
    private void doScan(){
        if(mBluetoothAdapter == null) return;
        L.logOnly("--现在开始扫描");
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
        new Thread(() -> mBluetoothAdapter.startLeScan(mLeScanCallback)).start();
        mHandler.postDelayed(() -> {
            if(mBluetoothAdapter != null && mLeScanCallback != null) mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }, 1000 * 5);
    }

    /** 扫描回调 */
    private void onScan(BluetoothDevice device1, int rssi, byte[] scanRecord){
        if(mDatas.contains(device1)) return;
        L.logOnly("--搜到设备:" + device1.getName() + ", Addr: " + device1.getAddress());
        mDatas.add(device1);
        mAdapter.notifyItemInserted(mDatas.size() - 1);
    }

    /** 初始化蓝牙适配器 */
    @SuppressLint("NewApi")
    private void initBleAdapter() {
        if(mBluetoothAdapter == null) return;
        L.logOnly("--开始打开蓝牙");
        if(mBluetoothAdapter != null) {
            mBluetoothAdapter.enable(); // 打开蓝牙
            return;
        }

        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        if(mBluetoothAdapter == null){
            TOAST.showShort(this, "很遗憾, 您的设备不支持蓝牙!");
            return;
        }
        mBluetoothAdapter.enable();     // 打开蓝牙
    }

    @Override
    protected void onPause() {
        super.onPause();
//        if(mProhibitViewGroup != null) BarUtils.allowStatusPanelDropDown(mWindowManager, mProhibitViewGroup);
//        BarUtils.unBanStatusBar(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        if(mWindowManager != null) mProhibitViewGroup = BarUtils.prohibitStatusPanelDropDown(this, mWindowManager);
//        BarUtils.banStatusBar(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.disable(); // 打开蓝牙
            return;
        }
    }

    @Override
    public void onClick(View v) {
        Object o = v.getTag();
        if(!(o instanceof BluetoothDevice)) return;
        switchToScan((BluetoothDevice) o);
    }

    private void switchToScan(BluetoothDevice device){
        if(TextUtils.isEmpty(device.getAddress())) {
            TOAST.showShort(this, "--无效设备");
            return;
        }

//        Intent intent = new Intent(this, ScanActivity.class);
        Intent intent = new Intent(this, InputBizIdActivity.class);
        intent.putExtra("bleAddr", device.getAddress());
        startActivity(intent);
    }

    /** 加载历史数据来判断是否要先到服务端注册绑定下 */
    private void adjustToLoadOrSwitch(){
        String topic = App.getApp().getTableMgr().getTbArg().queryByArgName(BizConstant.ARG_MQTT_TOPIC_KEY);
        if(TextUtils.isEmpty(topic)){
            L.logOnly("--没有发现历史数据");// 接下来不发生页面跳转, 只能手动绑定
            initBt();
            doLoad();
            return;
        }
        switchToMain();
    }

    private void switchToMain(){
        System.out.println("--直接跳转主页面");
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}
